/*
 * meituan.com Inc.
 * Copyright (c) 2010-2018 All Rights Reserved.
 */
package item09;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.util.Stack;

/**
 * <p>
 *
 * </p>
 * @author LvJing
 * @version $Id:StackToQueue.java v1.0 2018/7/14 下午2:09 LvJing Exp $
 */
public class StackToQueue {

    /**
     * 面试题8：用两个栈实现队列
     * 思路：根据栈和队列的特性，在队列入队时，往stack1中压栈，在队列出队时，由于要实现最先压栈的最先出去，则需要把栈中的元素移动到stack2，
     * 移动后stack2的顶部就是要出队的元素。如果再次出队，且stack1为空，直接弹栈stack2；如果stack1不为空，需要先把stack1的元素移动到stack2
     * 才能出队。
     */
    class Solution {

        private Stack<Integer> stack1 = new Stack<>();

        private Stack<Integer> stack2 = new Stack<>();

        void appendTail(int value) {
            stack1.push(value);
        }

        int deleteHead() {
            if (stack1.isEmpty() && stack2.isEmpty()) {
                throw new RuntimeException("Queue is NO data");
            }
            if (stack2.isEmpty()) {
                while (!stack1.isEmpty()) {
                    stack2.push(stack1.pop());
                }
            }

            return stack2.pop();
        }
    }

    private Solution solution;

    @Before
    public void init() {
        solution = new Solution();
    }

    /**
     * 往空的队列添加元素
     */
    @Test
    public void test01() {
        solution.appendTail(1);
        Assert.assertEquals(1, solution.deleteHead());
    }

    /**
     * 往空的队列里删除元素
     */
    @Test(expected = RuntimeException.class)
    public void test011() {
        solution.deleteHead();
    }

    /**
     * 往非空队列添加元素,删除元素
     */
    @Test
    public void test02() {
        solution.appendTail(1);
        solution.appendTail(1);
        solution.appendTail(5);
        Assert.assertEquals(1, solution.deleteHead());
    }

    /**
     * 连续删除元素直至不能删除
     */
    @Test
    public void test03() {
        solution.appendTail(1);
        solution.appendTail(2);
        solution.appendTail(3);
        Assert.assertEquals(1, solution.deleteHead());
        Assert.assertEquals(2, solution.deleteHead());
        Assert.assertEquals(3, solution.deleteHead());
    }
}
